package com.manli.api.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

public class FileUtil {
    public static void main(String[] args)throws Exception {
//        String filePath = "C:\\Users\\fjc\\Desktop\\浙江省联系方式.txt";
//        List<String> list = FileUtil.readTxtFile(filePath);
//
//        for(int i=0;i<list.size() / 3;i++){
//            System.out.println(list.subList(i*3,i*3 + 3));
//        }


        String basePath="C:\\Users\\fjc\\Desktop\\hangzhou";
        String[] list=new File(basePath).list();
        List<String> strings = Arrays.asList(list);
        System.out.println(strings);
    }

    public static List<String> readTxtFile(String filePath)throws Exception{

        String encoding="UTF-8";
        File file=new File(filePath);
        List<String> list = new ArrayList<>();
        if(file.isFile() && file.exists()) { //判断文件是否存在
            InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file), encoding);//考虑到编码格式
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;

            while ((lineTxt = bufferedReader.readLine()) != null) {

                if ("".equals(lineTxt)) {
                    continue;
                } else {
                    System.out.println(lineTxt);
                }
                list.add(lineTxt);
            }
            read.close();
        }
        System.out.println(list);
        return list;
    }

    public static File multipartFileToFile(MultipartFile file)throws Exception{

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            OutputStream os = new FileOutputStream(toFile);
            try {
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                os.close();
                ins.close();
                ins.close();
            }
        }
        return toFile;
    }
}
